var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// session 和 flash
var session = require('express-session')
var flash = require('connect-flash')
// ueditor
var ueditor = require("ueditor");
var moment = require('moment')




// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
var indexRouter = require('./routes/index')

var adminRouter = require('./routes/admin')

var app = express();




// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 配置session
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
  //cookie: { secure: true }   /*secure https这样的情况才可以访问cookie*/
}))

// 配置 消息提示 flash
app.use(flash())

//模板中需要用到的公共变量的分配
app.use(function(req, res, next) {
  //分配act 变量
  var path = req.originalUrl
  var pathObj = path.split('/')
  var act = pathObj[2]
  res.locals.act = act

  // 分配 success error
  res.locals.success = req.flash('success').toString()
  res.locals.error = req.flash('error').toString()

  // 分配登录后的user数据

  res.locals.user = req.session.user ? req.session.user : null
  // moment
  res.locals.moment = moment
  next()
})

//使用模块
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
  // ueditor 客户发起上传图片请求
  if (req.query.action === 'uploadimage') {
      var foo = req.ueditor;

      var imgname = req.ueditor.filename;

      var img_url = '/images/';
      res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
      res.setHeader('Content-Type', 'text/html');//IE8下载需要设置返回头尾text/html 不然json返回文件会被直接下载打开
  }
  //  客户端发起图片列表请求
  else if (req.query.action === 'listimage') {
      var dir_url = '/images/';
      res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
  }
  // 客户端发起其它请求
  else {
      // console.log('config.json')
      res.setHeader('Content-Type', 'application/json');
      res.redirect('/ueditor/config.json');
  }
}));

//前台路由
app.use('/', indexRouter)

//后台管理路由
app.use('/admin',adminRouter)







// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
